package com.lighting.smssystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.model.User;

import java.util.Map;

/**
 * Author LeeMaster
 */
public class JWTUtils {

    private static final String SECRET = "org.qiqiang.secret";
    private static final String ISSUER = "smsSystem";


    /**
     * create the jwt token to use
     * @param user
     * @return
     */
    public static String createJwt(User user){
        Algorithm algorithm = Algorithm.HMAC256(SECRET);

        JWTCreator.Builder builder = JWT.create();

        builder.withIssuer(ISSUER);
        builder.withClaim("userId",user.getUserId())
                .withClaim("userRole",user.getUserRole().code)
                .withClaim("userPhone",user.getUserPhone())
                .withClaim("timer", System.currentTimeMillis())
        ;

        return builder.sign(algorithm);
    }

    /**
     * 解析成为 User 对象
     * @param token
     * @return
     */
    public static User parseJwt(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();

            DecodedJWT jwt = verifier.verify(token);

            User user = new User();

            Map<String, Claim> map = jwt.getClaims();

            user.setUserId(map.get("userId").asLong());

            user.setUserRole(UserRole.parse(map.get("userRole").asInt()));

            user.setUserPhone(map.get("userPhone").asString());

            // 一天的毫秒
            int oneDay = 24 * 60 * 60 * 1000;

            Long timer = System.currentTimeMillis() - map.get("timer").asLong();
            if (timer > oneDay) {
                return null;
            }

            return user;
        }catch (Exception e){
            return null;
        }


    }

    /**
     * 验证是否合法的jwt
     * @param token
     * @return
     */
    public static boolean validateJwt(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();

            DecodedJWT jwt = verifier.verify(token);

            return true;
        }catch (Exception e){
            return false;
        }

    }
}
